import json
from flask import Flask, request, jsonify
from flask_cors import CORS
import requests

app = Flask(__name__)
CORS(app)


@app.route('/weather', methods=['GET'])
def get_weather():
    address = request.args.get('address')
    if not address:
        return jsonify({'error': 'address is required'}), 400

    try:
        # Call luckycola adcode API to get adcode information
        colaKey = "hdA9VriQXKkwDv1711679155024PxISI7S3YB"
        api_url = f"https://luckycola.com.cn/weather/geo?colaKey={
            colaKey}&address={address}"
        response = requests.get(api_url)
        if response.status_code != 200:
            return jsonify({'error': 'Failed to fetch adcode information'}), response.status_code
        adcode_data = response.json()

        adcode = adcode_data["data"]["geocodes"][0]["adcode"]
        print(adcode)

        # Call luckycola weather API to get weather information
        url = 'https://luckycola.com.cn/weather/getWeather'

        appKey = '660626d72fa3a73a48458699'
        uid = '1Ca5Tg1711679155024d5LxXNMyN9'
        body = {
            'appKey': appKey,
            'adcode': adcode,
            'uid': uid
        }
        body_json = json.dumps(body)
        response = requests.post(url, data=body_json, headers={
            'Content-Type': 'application/json'})
        if response.status_code != 200:
            return jsonify({'error': 'Failed to fetch weather information'}), response.status_code

        weather_data = response.json()
        print(weather_data)
    except requests.HTTPError as e:
        return jsonify({"error": f"Request error: {e.response.status_code}"}), e.response.status_code
    except requests.RequestException as e:
        return jsonify({"error": f"Server error: {e}"}), 500

    return jsonify(weather_data)


if __name__ == '__main__':
    app.run(debug=True)
